<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>商品信息</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div style="margin-top:30px">
      <template>
        <el-select v-model="selection" placeholder="搜索类型" style="width:110px">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </template>
      <el-input
        v-if="selection==1"
        v-model.number="selectId"
        placeholder="请输入商品id"
        style="width:400px"
      ></el-input>
      <el-input
        v-else-if="selection==2"
        v-model="selectName"
        placeholder="请输入商品名"
        style="width:400px"
      ></el-input>
      <!-- <el-input v-else-if="selection==3" v-model="selectCreateDate" placeholder="请选择起止日期" style="width:400px"></el-input> -->
      <el-date-picker
        v-else-if="selection==3"
        style="width:400px"
        v-model="selectCreateDate"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetimerange"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        align="right"
      ></el-date-picker>
      <!-- <el-input v-else v-model="selectUpdateDate" placeholder="请选择起止日期" style="width:400px"></el-input> -->
      <el-date-picker
        v-else-if="selection==4"
        style="width:400px"
        v-model="selectUpdateDate"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetimerange"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        align="right"
      ></el-date-picker>
      <el-input v-else placeholder="请先选择搜索类型" style="width:400px"></el-input>
      <el-button type="primary" plain style="margin-left:30px;" @click="search(1)">搜索</el-button>
      <el-button type="primary" plain style="margin-left:30px;" @click="reset">重置</el-button>
      <el-button type="primary" style="float:right;" @click="insertProduct">新增商品</el-button>
    </div>
    <el-table
      :data="products"
      border
      style="width: 100%; margin-top: 15px"
      @cell-mouse-enter="handleCellEnter"
      @cell-mouse-leave="handleCellLeave"
    >
      <el-table-column prop="productId" label="ID" width="50"></el-table-column>
      <el-table-column prop="productName" label="商品名">
        <div class="item" slot-scope="scope">
          <el-input class="item__input" v-model="scope.row.productName" placeholder="请输入内容"></el-input>
          <div class="item__txt">{{ scope.row.productName }}</div>
        </div>
      </el-table-column>

      <el-table-column prop="soldNum" label="已售数量" width="75">
        <div class="item" slot-scope="scope">
          <el-input class="item__input" v-model="scope.row.soldNum" placeholder="请输入内容"></el-input>
          <div class="item__txt">{{ scope.row.soldNum }}</div>
        </div>
      </el-table-column>

      <el-table-column prop="productStatus" label="商品状态">
        <template slot-scope="scope">
          <el-tooltip :content="'Switch value: ' + scope.row.productStatus" placement="top">
            <el-switch
              v-model="scope.row.productStatus"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              active-text="已上架"
              :inactive-value="0"
              inactive-text="已下架"
            ></el-switch>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column prop="content" label="商品内容">
        <div class="item" slot-scope="scope">
          <el-input class="item__input" v-model="scope.row.content" placeholder="请输入内容"></el-input>
          <div class="item__txt">{{ scope.row.content }}</div>
        </div>
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间">
        <!-- <div class="block" slot-scope="scope">
          <el-date-picker
            v-model="scope.row.createTime"
            type="datetime"
            placeholder="选择日期"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </div>-->
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间">
        <!-- <div class="block" slot-scope="scope">
          <el-date-picker
            v-model="scope.row.updateTime"
            type="datetime"
            placeholder="选择日期"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </div>-->
      </el-table-column>

      <el-table-column label="图片" width="50">
        <template slot-scope="scope">
          <el-button @click="editImg(scope.row.productId)" type="text" size="small">管理</el-button>
        </template>
      </el-table-column>

      <el-table-column label="评论" width="50">
        <template slot-scope="scope">
          <el-button @click="editCol(scope.row.productId)" type="text" size="small">管理</el-button>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button @click="saveProduct(scope.row.productId)" type="text" size="small">保存</el-button>
          <el-button type="text" size="small" @click="deleteProduct(scope.row.productId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="display: flex; justify-content: center">
      <el-pagination
        background
        layout="prev, pager, next"
        @current-change="goto"
        :total="total"
        :current-page="currentPage"
      ></el-pagination>
    </div>

    <el-dialog title="图片管理" :visible.sync="picDialog">
      <el-table
        :data="productPic"
        @cell-mouse-enter="handleCellEnter"
        @cell-mouse-leave="handleCellLeave"
      >
        <el-table-column property="id" label="ID" width="50"></el-table-column>
        <el-table-column property="isMain" label="是否为主图">
          <template slot-scope="scope">
            <!-- {{scope.row.isMain == 1? "主图":"非主图"}} -->
            <el-select v-model="scope.row.isMain">
              <el-option label="主图" value="1"></el-option>
              <el-option label="非主图" value="0"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column property="url" label="缩略图">
          <template slot-scope="scope">
            <img :src="scope.row.url | img" />
          </template>
        </el-table-column>
        <el-table-column property="createdTime" label="创建时间" width="180"></el-table-column>
        <el-table-column property="updatedTime" label="修改时间" width="180"></el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="saveImg(scope.row.id)" type="text" size="small">保存</el-button>
            <el-button type="text" size="small" @click="deleteImg(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8081/upload/"
          :show-file-list="false"
          :on-success="handleSuccess"
          :before-upload="beforeUpload"
          style="float:left"
        >
          <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>

        <el-button @click="picDialog = false">取 消</el-button>
        <el-button type="primary" @click="picDialog = false">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="评论管理" :visible.sync="comDialog">
      <el-table
        :data="productCom"
        @cell-mouse-enter="handleCellEnter"
        @cell-mouse-leave="handleCellLeave"
      >
        <el-table-column property="commId" label="ID" width="50"></el-table-column>
        <el-table-column property="userId" label="用户ID" width="50"></el-table-column>
        <el-table-column property="isAnonymous" label="是否匿名"></el-table-column>
        <el-table-column property="commType" label="评论类型">
          <template slot-scope="scope">
            <span v-if="(scope.row.commType = 1)">好评</span>
            <span v-else-if="(scope.row.commType = 0)">中评</span>
            <span v-else>差评</span>
          </template>
        </el-table-column>
        <el-table-column property="commContent" label="评论内容"></el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="deleteCom(scope.row.commId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="comDialog = false">取 消</el-button>
        <el-button type="primary" @click="comDialog = false">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="新增商品" :visible.sync="proDialog">
      <el-form :model="newProduct">
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="newProduct.productName" autocomplete="off" style="width:50%"></el-input>
        </el-form-item>
        <el-form-item label="商品状态" :label-width="formLabelWidth">
          <el-select v-model="newProduct.productStatus" placeholder="请选择商品状态" style="width:50%">
            <el-option label="上架" value="1"></el-option>
            <el-option label="下架" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品内容" :label-width="formLabelWidth">
          <el-input v-model="newProduct.content" autocomplete="off" style="width:50%"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="proDialog = false">取 消</el-button>
        <el-button type="primary" @click="uploadProduct">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import http from "@/core/httpRequest.js";
export default {
  data() {
    return {
      products: [],
      // productDetails: [],
      productPic: [],
      productCom: [],
      currentPage: 1,
      total: 0,
      picDialog: false,
      comDialog: false,
      proDialog: false,
      //新增商品信息
      newProduct: {
        comments: null,
        content: "",
        createTime: "",
        imgs: null,
        productId: null,
        productName: "",
        productStatus: "",
        soldNum: 0,
        updateTime: "",
      },
      //用于临时储存打开图片/评论管理时的商品ID
      itemId: 0,
      //用于搜索商品的选项
      options: [
        {
          value: "1",
          label: "商品id",
        },
        {
          value: "2",
          label: "商品名",
        },
        {
          value: "3",
          label: "创建时间",
        },
        {
          value: "4",
          label: "修改时间",
        },
      ],
      selection: "",
      selectId: "",
      selectName: "",
      selectCreateDate: "",
      selectUpdateDate: "",
      //记录搜素时的选择，以便于调整页码
      lastSelection: "",
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },

  mounted() {
    this.goto(1);
  },

  methods: {
    goto(page) {
      if (this.lastSelection == "" || this.lastSelection == null) {
        http.get(`/product/page?page=${page}`).then((res) => {
          this.products = res.data.data.products;
          this.total = res.data.data.total;
        });
      } else {
        switch (this.lastSelection) {
          case "1":
            http
              .get(`/product/searchId?productId=${this.selectId}`)
              .then((res) => {
                this.products = res.data.data;
                this.total = this.products.length;
              });
            break;
          case "2":
            http
              .get(
                `/product/searchName?productName=${this.selectName}&page=${page}`
              )
              .then((res) => {
                this.products = res.data.data.products;
                this.total = res.data.data.total;
              });
            break;
          case "3":
            http
              .post(`/product/searchCreateTime`, {
                page: page,
                limit: 10,
                beginTime: this.selectCreateDate[0],
                endTime: this.selectCreateDate[1],
              })
              .then((res) => {
                this.products = res.data.data.products;
                this.total = res.data.data.total;
              });
            break;
          case "4":
            http
              .post(`/product/searchUpdateTime`, {
                page: page,
                limit: 10,
                beginTime: this.selectUpdateDate[0],
                endTime: this.selectUpdateDate[1],
              })
              .then((res) => {
                this.products = res.data.data.products;
                this.total = res.data.data.total;
              });
            break;
        }
      }
      // http.get(`/product/all`).then((res) => {
      //   this.productDetails = res.data.data;
      // });
    },
    //头部搜索栏按钮
    reset() {
      this.selectId = "";
      this.selectName = "";
      this.selectCreateDate = "";
      this.selectUpdateDate = "";
    },
    search(page) {
      if (this.selection == "") {
        alert("请先选择搜索类型");
      } else {
        this.currentPage = 1;
        switch (this.selection) {
          case "1":
            if (this.selectId == "") {
              http.get(`/product/page?page=${page}`).then((res) => {
                this.products = res.data.data.products;
                this.total = res.data.data.total;
                this.lastSelection = "";
              });
            } else {
              http
                .get(`/product/searchId?productId=${this.selectId}`)
                .then((res) => {
                  this.products = res.data.data;
                  this.total = this.products.length;
                  this.lastSelection = this.selection;
                });
            }
            break;
          case "2":
            if (this.selectName == "") {
              http.get(`/product/page?page=${page}`).then((res) => {
                this.products = res.data.data.products;
                this.total = res.data.data.total;
                this.lastSelection = "";
              });
            } else {
              http
                .get(
                  `/product/searchName?productName=${this.selectName}&page=${page}`
                )
                .then((res) => {
                  this.products = res.data.data.products;
                  this.total = res.data.data.total;
                  this.lastSelection = this.selection;
                });
            }
            break;
          case "3":
            if (this.selectCreateDate == "") {
              http.get(`/product/page?page=${page}`).then((res) => {
                this.products = res.data.data.products;
                this.total = res.data.data.total;
                this.lastSelection = "";
              });
            } else {
              http
                .post(`/product/searchCreateTime`, {
                  page: page,
                  limit: 10,
                  beginTime: this.selectCreateDate[0],
                  endTime: this.selectCreateDate[1],
                })
                .then((res) => {
                  this.products = res.data.data.products;
                  this.total = res.data.data.total;
                  this.lastSelection = this.selection;
                });
            }
            break;
          case "4":
            if (this.selectUpdateDate == "") {
              http.get(`/product/page?page=${page}`).then((res) => {
                this.products = res.data.data.products;
                this.total = res.data.data.total;
                this.lastSelection = "";
              });
            } else {
              http
                .post(`/product/searchUpdateTime`, {
                  page: page,
                  limit: 10,
                  beginTime: this.selectUpdateDate[0],
                  endTime: this.selectUpdateDate[1],
                })
                .then((res) => {
                  this.products = res.data.data.products;
                  this.total = res.data.data.total;
                  this.lastSelection = this.selection;
                });
            }
            break;
        }
      }
    },
    //弹出图片和评论管理页面
    editImg(id) {
      this.picDialog = true;
      this.itemId = id;
      http.get(`/img/query?productId=${id}`).then((res) => {
        this.productPic = res.data.data;
      });
    },
    editCol(id) {
      this.comDialog = true;
      this.itemId = id;
      http.get(`/com/query?productId=${id}`).then((res) => {
        this.productCom = res.data.data;
      });
    },

    //将单元格设置成可编辑
    handleCellEnter(row, column, cell, event) {
      if (cell.querySelector(".item__txt")) {
        cell.querySelector(".item__txt").style.display = "none";
      }
      if (cell.querySelector(".item__input")) {
        cell.querySelector(".item__input").style.display = "block";
      }
    },
    handleCellLeave(row, column, cell, event) {
      if (cell.querySelector(".item__txt")) {
        cell.querySelector(".item__txt").style.display = "block";
      }
      if (cell.querySelector(".item__input")) {
        cell.querySelector(".item__input").style.display = "none";
      }
    },

    //保存商品数据
    saveProduct(id) {
      const updateTime = this.$moment(this.createTime).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      let product = this.products.filter((item) => item.productId == id)[0];
      product.updateTime = updateTime;
      http.post(`/product/update`, product).then((res) => {
        alert(res.data.message);
      });
    },
    deleteProduct(id) {
      if (confirm("是否删除此商品")) {
        http.get(`/product/delete?productId=${id}`).then((res) => {
          alert(res.data.message);
          http.get(`/product/page`).then((res) => {
            this.products = res.data.data.products;
            this.total = res.data.data.total;
          });
        });
      }
    },
    insertProduct() {
      this.proDialog = true;
    },
    uploadProduct() {
      const updateTime = this.$moment(this.createTime).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      this.newProduct.createTime = updateTime;
      this.newProduct.updateTime = updateTime;
      //将商品信息上传到数据库
      http.post(`/product/insert`, this.newProduct).then((r) => {
        alert(r.data.message);
        //重新加载商品信息
        http.get(`/product/page?page=${page}`).then((res) => {
                this.products = res.data.data.products;
                this.total = res.data.data.total;
              });
      });
      proDialog = false;
    },
    saveImg(id) {
      const updateTime = this.$moment(this.createTime).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      let img = this.productPic.filter((item) => item.id == id)[0];
      img.updatedTime = updateTime;
      http.post(`/img/update`, img).then((res) => {
        alert(res.data.message);
        http.get(`/img/query?productId=${this.itemId}`).then((res) => {
          this.productPic = res.data.data;
        });
      });
    },
    deleteImg(id) {
      if (confirm("是否删除此图片")) {
        http.get(`/img/delete?imgId=${id}`).then((res) => {
          alert(res.data.message);
          http.get(`/img/query?productId=${this.itemId}`).then((res) => {
            this.productPic = res.data.data;
          });
        });
      }
    },
    deleteCom(id) {
      if (confirm("是否删除此评论")) {
        http.get(`/com/delete?comId=${id}`).then((res) => {
          alert(res.data.message);
          http.get(`/com/query?productId=${this.itemId}`).then((res) => {
            this.productCom = res.data.data;
          });
        });
      }
    },
    //图片上传成功后回调
    handleSuccess(res, file) {
      var pic = {
        itemId: this.itemId,
        url: res.data.newName,
        createdTime: res.data.uploadTime,
        updatedTime: res.data.uploadTime,
        // id: null,
        // isMain: null,
        // sort: null,
      };
      //将图片信息上传到数据库
      http.post(`/img/insert`, pic).then((r) => {
        alert(r.data.message);
        //重新加载图片信息
        http.get(`/img/query?productId=${this.itemId}`).then((res) => {
          this.productPic = res.data.data;
        });
      });
    },
    //图片上传前验证大小
    beforeUpload(file) {
      const isLt20M = file.size / 1024 / 1024 < 20;
      if (!isLt20M) {
        this.$message.error("上传头像图片大小不能超过 20MB!");
      }
      return isLt20M;
    },
  },
};
</script>

<style>
.item__input {
  display: none;
}
.item__txt {
  display: block;
}
img {
  width: 100%;
  height: 100%;
}
</style>